package com.group15.phms;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class AlarmReceiverActivity extends Activity{
	
	private MediaPlayer mMediaPlayer; 
	DatabaseHelper db;
	SharedPreferences logins;
	String username;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_medication_monitor);
        
        db = new DatabaseHelper(getApplicationContext());
		logins = getSharedPreferences("logins",MODE_PRIVATE);
		username = logins.getString("currentUser","INVALID");
		String info = getMedicationInfo(db, username);
		String alarmMessage = "Attention!\nIt is time to take the following medication:\n" 
						+ info;
		//String alarmMessage = "Attention! It is time to take your medication.";
        TextView tv = (TextView)findViewById(R.id.medicationAlarm);
        tv.setText(alarmMessage);
        
        Button take = (Button) findViewById(R.id.takeMedicineButton); //take.setText("Take Medicine");
        Button snooze = (Button) findViewById(R.id.snoozeButton);//snooze.setText("Ignore");
        take.setOnClickListener(new View.OnClickListener() {
        	public void onClick(View v) {
        		mMediaPlayer.stop();
        		
        		//clear ignore count,user has taken medication
        		db = new DatabaseHelper(getApplicationContext());
        		logins = getSharedPreferences("logins",MODE_PRIVATE);
        		username = logins.getString("currentUser","INVALID");
        		String genericName = getMedicationName(db, username);
        		
        		db.setRetryCount(username, genericName, 0);
        		
        		finish();
        	}}); //end onClick.
        
        snooze.setOnClickListener(new View.OnClickListener() {
        	public void onClick(View v) {
        		mMediaPlayer.stop();
        		
        		//create a new alarm 10 minutes in future      		
        		db = new DatabaseHelper(getApplicationContext());
        		logins = getSharedPreferences("logins",MODE_PRIVATE);
        		username = logins.getString("currentUser","INVALID");
        		//get medication name
        		String genericName = getMedicationName(db, username);
        		
        		//count the number of ignores
        		int count = db.getRetryCount(username, genericName); 
        		db.setRetryCount(username, genericName, count++);
        		
        		//if ignoreCount > 3 send SMS to contacts
        		if( count >= 3){//send sms to contacts
        			//format message to send to user
        			String user = db.getUser(username).getName();
    				String message = "Attention: "+ user +" has not taken their " + genericName + " today," +
    						" please contact them to ensure they are ok. Thanks -DroidMD";
        			List<Contact> contacts = db.getContacts(username);
        			for(int i=0; i< contacts.size(); i++){ //send sms to each contact
        				//get users phone number
        				String phoneNumber = contacts.get(i).getPhone();

        				//send SMS with Event information to user
        				SmsManager sms = SmsManager.getDefault(); 
        				sms.sendTextMessage(phoneNumber, null, message, null, null);
        				
        				//reset count to zero
        				db.setRetryCount(username, genericName, 0);
        			}
        			
        		}
        		else{ //count is < 3 so make a new alarm 10 minutes from now
        			MedicationMonitor mm = new MedicationMonitor();
            		mm.createTempNotification(db.getMedicationInfo(genericName, username), 
            				Calendar.getInstance().getTimeInMillis(),count, getApplicationContext());
            		
        		}
        		
        		finish();
        	}}); //end onClick.

       playSound(this, getAlarmUri());        
    }

    private void playSound(Context context, Uri alert) {
        mMediaPlayer = new MediaPlayer();
        try {
            mMediaPlayer.setDataSource(context, alert);
            final AudioManager audioManager = (AudioManager) context
                .getSystemService(Context.AUDIO_SERVICE);
            if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
                mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
                mMediaPlayer.prepare();
                mMediaPlayer.start();
            }
        } catch (IOException e) {
             System.out.println("OOPS");
        }
    }

    //Get an alarm sound. Try for an alarm. If none set, try notification, 
    //Otherwise, ringtone.
    private Uri getAlarmUri() {
        Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
        if (alert == null) {
            alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            if (alert == null) {
            alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
            }
        }
        return alert;
    }

     private String getMedicationInfo(DatabaseHelper db, String username){
		String medInfo = "";
		Date rightNow = new Date();
		List<Medication> meds = db.getMedications(username);
		for(int i=0; i<meds.size(); i++){
			List<Dose> doses = db.getDoses(username, meds.get(i).getGenName());
			for(int j=0; j<doses.size(); j++){
				if(doses.get(j).getHour() == rightNow.getHours() && doses.get(j).getMinute() == rightNow.getMinutes() ){
					medInfo =  meds.get(i).getGenName() + "\nDosage: " + doses.get(j).getAmount() + doses.get(j).getType();
					break;
				}
			}
			if(!medInfo.equals("")){ break; }
		}
    	return medInfo;
    }
    
    private String getMedicationName(DatabaseHelper db, String username){
		String medInfo = "";
		Date rightNow = new Date();
		List<Medication> meds = db.getMedications(username);
		for(int i=0; i<meds.size(); i++){
			List<Dose> doses = db.getDoses(username, meds.get(i).getGenName());
			for(int j=0; j<doses.size(); j++){
				if(doses.get(j).getHour() == rightNow.getHours() && doses.get(j).getMinute() == rightNow.getMinutes() ){
					medInfo =  meds.get(i).getGenName();
					break;
				}
			}
			if(!medInfo.equals("")){ break; }
		}
    	return medInfo;
    }
}
